<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>修改内容与值</h3>
<button type="button" onclick="changeText()">Try it</button>
<p id="section">点击此段落时内容会被修改</p>

<h1 onclick="changeHeadText(this)">点击此标题内容会被修改</h1>

<p>输入的英文字母基于onkeyup事件，自动转为大写</p>
<input type="text" onkeyup="upperCase(this)">
<hr>
<h3>修改元素的其他属性</h3>
<div class="nav">
    <button type="button" onclick="changeColor()">点击随机改变此div下所有p的字体颜色</button>
    <p>Lorem ipsum dolor sit amet.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci assumenda doloribus expedita quam qui velit.
        Quia?</p>
</div>
<hr>
<p>修改input元素的类型</p>
<button type="button" onclick="changeInputType()">
    点击修改输入框为checkbox</button><br>
输入框：<input type="text" name="username">
<hr>
<p>仅当选择同意后，才能提交</p>
<form id="register">
    <label>
        <input type="checkbox" onchange="checkAgree(this)">
        已阅读并同意条款</label><br>
    <button type="submit" disabled>提交</button>
</form>
<hr>
<h3>Arrays Filter</h3>
<p>选择课程后，传递ID值，从JS数组中过滤出对象，显示在下面</p>
<select name="course" onchange="loopFilter(this.value)">
    <option></option>
    <option value="1">Java</option>
    <option value="2">C++</option>
</select>
<span id="teacherName"></span>

<script>
    let changeText = () => {
        document.getElementById("section").innerHTML = "changed by JS";
    };

    let changeHeadText = (h) => {
        h.innerHTML = "Ooooops!";
    };

    let upperCase = (input) => {
        input.value = input.value.toUpperCase();
    };
    /* ------------------------- */
    /* querySelectorAll()方法，基于CSS选择器，返回的是集合，不是数组 */
    let changeColor = () => {
        let ps = document.querySelectorAll("div.nav>p");
        // 四舍五入生成一个0-255的随机数
        let r = Math.round(Math.random() * 255);
        let g = Math.round(Math.random() * 255);
        let b = Math.round(Math.random() * 255);
        // 修改全部字体色
        ps.forEach(p => {
            // 基于模板字符串，避免使用加号拼接字符串与变量
            p.style.color = `rgb(${r}, ${g}, ${b})`;
        });
    }
    /* ------------------------------- */

    let changeInputType = () => {
        let input = document.querySelector("input[name=username]");
        input.type = input.type === "text" ? "checkbox" : "text";
    }
    /* ---------------------- */
    let checkAgree = (c) => {
        let submitButton = document.querySelector("#register button[type=submit]");
        /* 提交按钮的不可用状态与checkbox的选中状态正好相反 */
        submitButton.disabled = !c.checked;
    }
    /* --------------------- */
    let loopFilter = (id) => {
        let courses = [
            {id: 1, name: "Java", teacher: "BO"},
            {id: 2, name: "C++", teacher: "SUN"}
        ];
        let course = courses.find(c => c.id == id);
        document.getElementById("teacherName").innerHTML =
            course != null ? course.teacher : "";
    }
</script>
</body>
</html>